package test

import (
	"encoding/json"
	"errors"
	"lark/consts"
	"lark/proto"
	"lark/util"
	"net"
	"strings"
	"time"
)

var cgipass = "tcp://127.0.0.1:14567"
var serviceName = "lark-test-service"

func startServer() {
	x := strings.Split(cgipass, "://")
	network := x[0]
	addr := x[1]

	go businessServer(network, addr)

	time.Sleep(time.Second * 2)
	ping()
}

type serviceRegistInfo struct {
	Ip          string `json:"ip"`
	Port        int    `json:"port"`
	ServiceName string `json:"service"`
	WorkNum     int    `json:"worker_num"`
	CgiPass     string `json:"cgi_pass"`
}

func ping() {
	localIP, err := util.LocalIPByHostsFile()
	panicErr(err)

	info := serviceRegistInfo{
		Ip:          localIP,
		Port:        12345,
		ServiceName: serviceName,
		WorkNum:     10,
		CgiPass:     cgipass,
	}

	list := map[string][]string{
		"devcd": []string{"192.168.69.6:22379"},
	}

	for {
		conn, err := net.DialTimeout("tcp", "127.0.0.1:12312", time.Second)
		panicErr(err)

		b1, _ := json.Marshal([]serviceRegistInfo{info})
		b2, _ := json.Marshal(list)

		proto.NewTLVParser(conn).Send(time.Second, consts.Ps2lsmTagRegistReq, b1, b2)

		conn.Close()
		time.Sleep(time.Second * 3)
	}
}

func panicErr(err error) {
	if err != nil {
		panic(err)
	}
}

func businessServer(network, addr string) {
	l, err := net.Listen(network, addr)
	panicErr(err)

	for {
		conn, err := l.Accept()
		panicErr(err)

		go handle(conn)
	}
}

func handle(conn net.Conn) {
	p := proto.NewlarkProtoV2(conn, time.Second*10, time.Second*10)
	defer p.Close()

	for {
		tag, payload, err := p.Read()
		if err != nil {
			panicErr(err)
			return
		}

		if tag != consts.Lsp2psTagTaskReq {
			panicErr(errors.New("tag wrong"))
			return
		}

		err = p.Write(consts.Lsp2psTagTaskRespOK, proto.SplitPayload(payload)[0], nil)
		if err != nil {
			panicErr(err)
			return
		}
	}
}
